﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Core;
using Autofac.Features.Metadata;

namespace BitwiseOre.SharedMemory.Autofac
{
    internal static class ResolutionExtensions
    {
        public static T ResolveRoot<T>(
            this ILifetimeScope parent,
            Func<DependencyResolutionException, Exception> wrapException,
            params Parameter[] parameters)
        {
            try
            {
                var scope = parent.BeginLifetimeScope();
                var metaroot = scope.Resolve<Meta<Lazy<T>>>(parameters);

                if (metaroot.Metadata.ContainsKey(MetadataConstants.RootConfigKey))
                {
                    var configtype = (Type) metaroot.Metadata[MetadataConstants.RootConfigKey];
                    scope.Resolve<ResolveRootContext>(new TypedParameter(typeof (Type), configtype));
                    scope.Resolve(configtype, parameters);
                }

                return metaroot.Value.Value;
            }
            catch (DependencyResolutionException e)
            {
                var exception = wrapException(e);
                if (exception != null) throw exception;
                throw;
            }
        }

        public static TConfig ResolveConfig<TConfig>(this IComponentContext context)
        {
            return context.ResolveKeyed<TConfig>(context.Resolve<ResolveRootContext>().ConfigKey);
        }

        public static object ResolveConfig(this IComponentContext context, Type configType)
        {
            return context.ResolveService(new KeyedService(context.Resolve<ResolveRootContext>().ConfigKey,
                                                           configType));
        }
    }
}